<template>
  <div class="flex justify-end">
    <a-button @click="addOpen">新增</a-button>
  </div>

  <BasicModal
    v-bind="$attrs"
    :title="'新增合同'"
    @register="registerInformationModal"
    width="700px"
    @ok="handleSubmit"
    @cancel="closeFunc"
  >
    <PageWrapper>
      <!-- <p class="h-20" v-for="index in 20" :key="index">根据屏幕高度自适应</p> -->
      <BasicForm
        ref="formElRef1"
        @register="register"
        :showSubmitButton="false"
        :model="modelRef"
        :showResetButton="false"
      />
      <div class="ml-14">合同文件</div>
      <uploadImage class="ml-14" :fileList="fileList" :batchId="fileListBatchId" />
    </PageWrapper>
  </BasicModal>

  <BasicTable
    @register="registerTable"
    @edit-change="handleEditChange"
    @selection-change="selectionChange"
    :modal="setModalRef"
  >
    <template #bodyCell="{ column, record }">
      <template v-if="column.key === 'status'">
        <span>{{ record.status == 1 ? '过期' : '有效' }}</span>
      </template>
      <template v-if="column.key === 'contractTime'">
        <span>{{ dayjs(record.contractTime).format('YYYY-MM-DD') }}</span>
      </template>
      <template v-if="column.key === 'startTime'">
        <span
          >{{ dayjs(record.startTime).format('YYYY-MM-DD') }}至{{
            dayjs(record.endTime).format('YYYY-MM-DD')
          }}</span
        >
      </template>
      <template v-if="column.key === 'file'">
        <span @click="editUpload(record)" class="upload">
          <a-button type="primary" :size="'small'" class="ml-5">编辑</a-button>
          <!-- <span style="color: #0960bd" class="ml-5">编辑</span> -->
        </span>
        <div v-if="record.userFilesList.length > 0" class="">
          <div v-for="item in record.userFilesList" :key="item.batchId">
            <div class="flex">
              <div class="widthStyle">{{ item.fileOriginName }}</div>
              <preview-btn :fileUrl="item.fileUrl" :fileName="item.fileOriginName" />
              <file-download-btn :fileUrl="item.fileUrl" :fileName="item.fileOriginName" />
            </div>
          </div>
        </div>
      </template>
      <template v-if="column.key === 'check'">
        <a-button type="primary" size="mini" class="mr-2" @click="checked(record)">查看</a-button>
      </template>
    </template>
  </BasicTable>
</template>
<script lang="ts" setup>
  import { ref, unref, onMounted, nextTick } from 'vue';
  import { BasicTable, useTable } from '@/components/Table';
  import dayjs from 'dayjs';
  import PreviewBtn from '@/components/common/PreviewBtn.vue';
  import { getContractRecordAPI, addContractRecord } from '@/api/eslogis-tps/index';
  import { addContractSchema } from './AddContract';
  import uploadImage from './uploadImage.vue';
  import FileDownloadBtn from '@/components/common/FileDownloadBtn.vue';
  import { BasicModal, useModal } from '@/components/Modal';

  import { BasicForm, useForm } from '@/components/Form';
  import { useMessage } from '@/hooks/web/useMessage';
  import { buildUUID } from '@/utils/uuid';
  import { createPrompt } from '@/components/Prompt';

  // const uuid = buildUUID();

  const { createMessage } = useMessage();
  // let list: any[] = reactive([]);
  const columns = [
    {
      title: '合同编号',
      dataIndex: 'contractCode',
    },
    {
      title: '签订日期',
      dataIndex: 'contractTime',
    },
    {
      title: '合作期限',
      dataIndex: 'startTime',
    },
    {
      title: '状态',
      dataIndex: 'status',
    },
    {
      title: '合同附件',
      dataIndex: 'file',
    },
    {
      title: '计费规则',
      dataIndex: 'check',
    },
  ];
  const [registerInformationModal, { openModal, closeModal }] = useModal();
  const emit = defineEmits(['checked', 'reload']);
  const [registerTable, { reload }] = useTable({
    columns: columns,
    showIndexColumn: false,
    immediate: false,
    api: getContractRecordAPI,
    beforeFetch: (params) => {
      return { contractId: contractId.value, ...params };
    },
    scroll: { y: '100%' },
    pagination: true,
    showTableSetting: false,
    showSelectionBar: false, // 显示多选状态栏
  });
  const [register, { validate: addContractForm, resetFields, setFieldsValue }] = useForm({
    layout: 'vertical',
    baseColProps: {
      span: 6,
    },
    schemas: addContractSchema,
  });
  const modelRef = ref({});
  const tempId = ref('');
  const fileList = ref([]);
  const formElRef1 = ref<Nullable<any>>(null);
  const fileListBatchId = ref('');
  const contractId = ref('');
  onMounted(() => {
    contractId.value = id ? id : '';
    console.log('🚀 ~ onMounted ~ id:', id);
  });
  // function checkFile(file) {
  //   console.log(file);
  // }
  // 获取外部传入的数据
  const { data, id } = defineProps({
    data: {
      type: Array,
      default: () => {
        return {};
      },
    },
    id: {
      type: String,
      default: () => {
        return '';
      },
    },
  });

  // list = data;
  function checked(record) {
    console.log('🚀 ~ checked ~ record:', record);
    createPrompt({
      title: '请选择模板类型',
      required: true,
      label: '模板类型',
      onOK: async ({ label, value }) => {
        emit('checked', {
          contractId: record.id,
          freightType: label,
          freightTypeId: value,
        });
      },
      inputType: 'Select',
      componentProps: {
        labelInValue: true,
        options: [
          {
            label: '陆运',
            value: 1,
          },
          {
            label: '海运20',
            value: 2,
          },
          {
            label: '海运40',
            value: 3,
          },
        ],
      },
    });
  }
  function editUpload(item) {
    tempId.value = item.id;
    item.contractStartEndTime = [
      dayjs(item.startTime).format('YYYY-MM-DD'),
      dayjs(item.endTime).format('YYYY-MM-DD'),
    ];
    openModal(true);
    nextTick(async () => {
      if (item.batchId) {
        fileList.value = item.userFilesList;
        fileListBatchId.value = item.batchId;
        const formEl1 = unref(formElRef1);
        await formEl1.setProps({ disabled: true });
        setFieldsValue({ ...item });
      }
    });
  }
  async function handleSubmit() {
    try {
      const addContractSchema = await addContractForm();
      const { contractCode, contractTime, contractStartEndTime } = addContractSchema;
      const startTime = contractStartEndTime[0];
      const endTime = contractStartEndTime[1];
      const params = {
        contractCode,
        contractId: contractId.value,
        contractTime: contractTime + ' 00:00:00',
        startTime: startTime + ' 00:00:00',
        endTime: endTime + ' 00:00:00',
        batchId: fileListBatchId.value,
        mid2: data.mid2,
        type: 1,
      };
      if (tempId.value) {
        params.id = tempId.value;
        createMessage.success('处理成功');
        emit('reload');
        const searchInfo = unref({});
        reload({ searchInfo });
        closeModal();
        return;
      }
      addContractRecord(params).then((res) => {
        console.log(res);

        createMessage.success('处理成功');
        emit('reload');
        const searchInfo = unref({});
        reload({ searchInfo });
        closeModal();
      });
    } catch (error) {
      console.log(error);
    }
  }
  function addOpen() {
    resetFields();
    openModal(true);
    tempId.value = '';
    fileListBatchId.value = buildUUID();
    nextTick(async () => {
      fileList.value = [];
      const formEl1 = unref(formElRef1);
      await formEl1.setProps({ disabled: false });
    });
  }
  function closeFunc() {
    tempId.value = '';
    (fileListBatchId.value = ''), (fileList.value = []);
    resetFields();
  }

  function getList(id) {
    console.log('🚀 ~ getList ~ getList:', data.contractInfo, id);
    contractId.value = id ? id : contractId.value;
    reload();
  }

  defineExpose({
    getList,
  });
</script>

<style scoped>
  ::v-deep .ant-picker {
    width: 100%;
  }

  /* ::v-deep .ant-upload.ant-upload-select {
    width: 60px !important;
    height: 60px !important;
  } */

  ::v-deep .anticon {
    /* display: none; */
  }

  .upload:hover {
    cursor: pointer;
  }

  .widthStyle {
    /* height: 32px; */
    display: inline-block;

    /* margin-bottom: 3px; */
    width: 100px;
    overflow: hidden; /* 隐藏超出容器的内容 */
    line-height: 32px;
    text-overflow: ellipsis; /* 使用省略号表示被截断的文本 */
    white-space: nowrap; /* 确保文本在一行内显示 */
  }
</style>
